import React, { Component, Fragment } from 'react'
import { Input, Button, List } from 'antd';
import store from '../store'
import * as Actions from '../store/actionCreator'
import { CSSTransition, TransitionGroup } from 'react-transition-group'
import './style.css'
class TodoList extends Component {
  constructor(props) {
    super(props)
    this.state = store.getState()

    this.handleBtnClick = this.handleBtnClick.bind(this)
    this.handleInputChange = this.handleInputChange.bind(this)
    this.handleDelClick = this.handleDelClick.bind(this)

    this.handleStoreChange = this.handleStoreChange.bind(this)
    store.subscribe(this.handleStoreChange)
  }

  render() {
    return (
      <Fragment>
        <div className="div-box">
          <label htmlFor="inputArea">输入内容</label>
          <Input placeholder="todo info"
            id="inputArea"
            className="input"
            onChange={this.handleInputChange}
            value={this.state.inputValue} />
          <Button type="primary"
            onClick={this.handleBtnClick}>提交
          </Button>
        </div>
        <div className="div-list">
          {this.state.list.length !== 0 && this.getTodoItem()}
        </div>
      </Fragment >
    )
  }
  getTodoItem() {
    return (
      <List bordered={true}>
        <TransitionGroup>
          {
            this.state.list.map((item, index) =>
              (
                <CSSTransition key={item} timeout={1000} classNames="fade">
                  <List.Item onClick={() => this.handleDelClick(index)}>{item}</List.Item>
                </CSSTransition>
              )
            )
          }
        </TransitionGroup>
      </List>
    )
  }
  // 订阅State变化
  handleStoreChange() {
    this.setState(store.getState())
  }
  // 处理输入框变更
  handleInputChange(e) {
    const value = e.target.value
    store.dispatch(Actions.getInputChangeAction(value))
  }
  // 处理单击添加
  handleBtnClick() {
    const value = this.state.inputValue;
    if (value) {
      store.dispatch(Actions.getAddListAction())
    }
  }
  // 处理单击删除
  handleDelClick(index) {
    store.dispatch(Actions.getDelListAction(index))
  }
}

export default TodoList
